#include "LevelTerrainHolder.h"
#include "BitmapLoader.h"
#include <iostream>
#include <fstream>
#include <cassert>
#include <allegro5/allegro_native_dialog.h>

using namespace std;

LevelTerrainHolder *LevelTerrainHolder::levelTH = NULL;

LevelTerrainHolder::LevelTerrainHolder(const char* path) {
    char buff[512], ch=' ', bitmap[50], terrain_conf[50], id[50];
	BitmapLoader bitmapLoader;
    ifstream cfg(path);
	
    while(!cfg.eof()) {
		ch = cfg.peek();
        if(ch != '#' && ch != '\n') {
            cfg.getline(buff, 512);
            sscanf(buff, "bitmap=%s id=%s conf=%s", bitmap, id, terrain_conf);
            //fprintf(stderr, "%s %s %s\n",  bitmap, id, terrain_conf);
			LevelTerrain* terrain = new LevelTerrain(bitmap, terrain_conf, id);
			//read_terrainConf(terrain_conf, terrain);
			levelTerrainMap[id] = terrain;
        }
		else {
			cfg.ignore(512, '\n');
		}
		ch = cfg.peek();
		if(ch == ' ') break;
    }
	cfg.close();
} 

LevelTerrainHolder::~LevelTerrainHolder()	{ 
	levelTerrainMap.clear(); 
}

void LevelTerrainHolder::Initialize(const char *path) { levelTH = new LevelTerrainHolder(path); }

LevelTerrainHolder *LevelTerrainHolder::GetSingleton(void) { 
	assert(levelTH);
	return levelTH; 
}

const LevelTerrain *LevelTerrainHolder::GetTerrain (const std::string id) const {
	LevelTerrainMap::const_iterator i = levelTerrainMap.find(id);
	assert(i!=levelTerrainMap.end());
	return i->second;
}
